package com.hyz.reggie.controller;

import com.hyz.reggie.common.RedisKeys;
import com.hyz.reggie.common.SendSms;
import com.hyz.reggie.common.ValidateCodeUtils;
import com.hyz.reggie.dto.LoginDto;
import com.hyz.reggie.pojo.R;
import com.hyz.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService service;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody LoginDto loginDto) {
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        System.out.println(code);
        //SendSms.sendMsg(loginDto.getPhone(), code + "");
        //HttpSession session = request.getSession();
        //session.setAttribute(loginDto.getPhone(), code);
        redisTemplate.opsForValue().set(RedisKeys.RG_CODE+loginDto.getPhone(),code,5, TimeUnit.MINUTES);
        return R.success("发送验证码成功,五分钟内有效~");
    }

    @PostMapping("/login")
    public R login(@RequestBody LoginDto loginDto) {
        boolean flag = service.login(loginDto);
        return flag ? R.success("登陆成功~") : R.error("登录失败~");
    }
    @PostMapping("/loginout")
    public R loginOut(){
        service.loginOut();
        return R.success("退出成功~");
    }
}
